<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 级联选择器 -->
      <el-row class="cascader_header">
        <span>选择商品分类：</span>
        <el-cascader
          v-model="selectKeys"
          :options="classifylist"
          :props="paramsProps"
          @change="handleChange"
          clearable
        ></el-cascader>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabChange">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="this.selectKeys.length !== 3 ? true : false"
            @click="dialogAddParamsVisible = true"
            >添加参数</el-button
          >
          <el-table :data="ManyTableData" style="width: 100%" border>
            <!-- 扩展列 -->
            <el-table-column type="expand">
              <!-- 插槽 -->
              <template slot-scope="scope">
                <!-- {{ scope.row.attr_vals }} -->
                <!-- 扩展列表 -->
                <div class="expand_box">
                  <!-- 标签页 -->
                  <el-tag
                    :key="i"
                    v-for="(tag, i) in scope.row.attr_vals"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(scope.row,i)"
                  >
                    {{ tag }}
                  </el-tag>
                  <!-- 输入框 -->
                  <el-input
                    class="input-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!-- 按钮 -->
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                  <!-- {{ scope.row }} -->
                </div>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- {{ scope.row }} -->
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editTableParams(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteTableParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="this.selectKeys.length !== 3 ? true : false"
            @click="dialogAddParamsVisible = true"
            >添加属性</el-button
          >
          <el-table :data="OnlyTableData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <div class="expand_box">
                  <!-- {{ scope.row }} -->
                  <!-- 标签页 -->
                  <el-tag
                    :key="i"
                    v-for="(tag, i) in scope.row.attr_vals"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(scope.row,i)"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                    class="input-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  class="el-icon-edit"
                  @click="editTableParams(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  class="el-icon-delete"
                  @click="deleteTableParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + this.titleText"
      :visible.sync="dialogAddParamsVisible"
      :close-on-click-modal="false"
      @close="resetDialogAddParams"
    >
      <el-form
        :model="AddParams"
        label-width="80px"
        :rules="AddParamsRules"
        ref="AddParamsRef"
        status-icon
      >
        <el-form-item :label="this.titleText" prop="attr_name">
          <el-input v-model="AddParams.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="subAddManyParams">提交</el-button>
        <el-button @click="resetDialogAddParams">重置</el-button>
      </div>
    </el-dialog>
    <!-- 编辑参数对话框 -->
    <el-dialog
      :title="'修改' + this.titleText"
      :visible.sync="dialogEditParamsVisible"
      :close-on-click-modal="false"
      @close="resetDialogEditParams"
    >
      <el-form
        :model="EditParams"
        :rules="EditParamsRules"
        ref="EditParamsRef"
        label-width="80px"
      >
        <el-form-item :label="this.titleText" prop="attr_name">
          <el-input v-model="EditParams.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="subEditManyParams(EditParams)"
          >提交</el-button
        >
        <el-button @click="dialogEditParamsVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      // 可选择的数据源
      classifylist: [],
      // 选中的数组集合
      selectKeys: [],
      // 级联选择器的配置参数
      paramsProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      // 被激活的标签页默认
      activeName: "many",
      // 动态标签页的数据
      ManyTableData: [],
      // 添加参数对话框
      dialogAddParamsVisible: false,
      // 添加动态参数的对象
      AddParams: {
        attr_name: "",
      },
      // 添加参数的规则校验
      AddParamsRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      // 静态属性的表格
      OnlyTableData: [],
      // 控制输入框自动获取焦点
      // isAutofocus: true,

      // 控制编辑对话框
      dialogEditParamsVisible: false,
      // 编辑对话框的校验规则
      EditParamsRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      // 编辑对话框的对象
      EditParams: {
        attr_name: "",
      },
    };
  },
  created() {
    this.getClassifylist();
  },
  methods: {
    // 加载级联选择器
    getClassifylist() {
      axios
        .get(`categories`)
        .then(({ data: res }) => {
          console.log(res);
          this.classifylist = res.data;
        })
        .catch(() => {
          this.$message.error("获取参数列表失败");
        });
        
    },
    // 更改级联选择器事件
    handleChange() {
      this.getParamsList();
    },
    // 获取参数列表
    async getParamsList() {
      if (this.selectKeys.length !== 3) {
        this.selectKeys = [];
        this.ManyTableData = [];
        this.OnlyTableData = [];
      }
      const { data: res } = await this.$http.get(
        `categories/${this.catId}/attributes`,
        { params: { sel: this.activeName } }
      );
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取动态参数列表失败");
      }
      // 整理扩展列标签数据，遍历每一项使其成为以逗号分割的数组
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        // 控制输入框显示与隐藏
        item.inputVisible = false;
        // 扩展列的输入框
        item.inputValue = "";
      });
      console.log(res.data);
      if (this.activeName === "many") {
        this.ManyTableData = res.data;
      } else {
        this.OnlyTableData = res.data;
      }
    },

    //更改标签页的事件
    handleTabChange() {
      this.getParamsList();
    },

    // 监听对话框关闭事件
    resetDialogAddParams() {
      this.$refs.AddParamsRef.resetFields();
    },
    // 提交添加动态参数
    subAddManyParams() {
      this.$refs.AddParamsRef.validate((valid) => {
        if (!valid) return;
        console.log(this.activeName);
        axios
          .post(`categories/${this.catId}/attributes`, {
            attr_name: this.AddParams.attr_name,
            attr_sel: this.activeName,
          })
          .then(({ data: res }) => {
            console.log(res,123);
            this.dialogAddParamsVisible = false;
            this.getParamsList();
            this.$message.success("添加参数成功");
          })
          .catch(() => {
            this.dialogAddParamsVisible = false;
            this.$message({
              type: "error",
              message: "添加参数失败",
            });
          });
      });
    },
    // 删除参数
    deleteTableParams(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          axios
            .delete(`categories/${this.catId}/attributes/${id}`)
            .then(({ data: res }) => {
              console.log(res);
              this.getParamsList();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            })
            .catch(() => {
              this.$message({
                type: "error",
                message: "删除失败!",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 点击标签事件
    handleClose(row,i) {
      row.attr_vals.splice(i,1);
      this.submitParams(row);
    },
    // 触发输入框显示
    showInput(rowInfor) {
      rowInfor.inputVisible = true;
      // 文本框自动获取焦点
      // 通过使用$nextTick这个方法，将页面成功渲染之后再调用回调函数里面的代码。若不用渲染之后获取焦点，当前页面还是原来的button元素，无输入框input元素
      this.$nextTick((_) => {
        // 通过$refs获取到输入框原生的input添加.focus()方法，获取文本框焦点
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    // 输入框失去焦点或点击 enter 键 开启的事件
    handleInputConfirm(rowInfor) {
      // 判断输入框是否有有效值,可以判断清楚空格后inputValue的长度是否为0
      if (rowInfor.inputValue.trim().length === 0) {
        rowInfor.inputValue = "";
        rowInfor.inputVisible = false;
        return;
      }
      // console.log("ok");
      // console.log(rowInfor.inputValue);
      // console.log(rowInfor, 123);
      // arr.push()方法是直接在原数组的后面添加新的元素，返回值为新数组的长度
      rowInfor.attr_vals.push(rowInfor.inputValue);
      rowInfor.inputValue = "";
      rowInfor.inputVisible = false;
      // 将前端的数组转换为以逗号相接的字符串     
      // rowInfor.attr_vals.join();
      this.submitParams(rowInfor);
    },
    // 编辑提交方法
    submitParams(rowInfor) {
      axios
        .put(`categories/${this.catId}/attributes/${rowInfor.attr_id}`, {
          attr_name: rowInfor.attr_name,
          attr_sel: this.activeName,
          attr_vals: rowInfor.attr_vals.join(),
        })
        .then(({ data: res }) => {
          console.log(res);
          this.$message.success("更新参数成功");
          this.getParamsList();
        })
        .catch(() => {
          this.$message({
            type: "error",
            message: "更新参数失败",
          });
        });
    },
    // 查询编辑id
    editTableParams(row) {
      axios
        .get(`categories/${this.catId}/attributes/${row.attr_id}`, {
          params: { attr_sel: row.activeName, attr_vals: row.attr_vals },
        })
        .then(({ data: res }) => {
          console.log(res);
          this.EditParams = res.data;
          this.dialogEditParamsVisible = true;
        })
        .catch(() => {
          this.$message({
            type: "error",
            message: "获取参数id失败",
          });
        });
    },
    // 重置编辑表单
    resetDialogEditParams() {
      this.$refs.EditParamsRef.resetFields();
    },
    // 提交编辑表单
    subEditManyParams() {
      this.$refs.EditParamsRef.validate((valid) => {
        if (!valid) return;
        // this.submitParams(this.EditParams);
        axios.put(`categories/${this.catId}/attributes/${this.EditParams.attr_id}`,
        {attr_name:this.EditParams.attr_name,attr_sel:this.EditParams.attr_sel})
        .then(({data:res})=> {
          console.log(res,'8848');
          this.EditParams = res.data;
          this.dialogEditParamsVisible = false;
          this.getParamsList();
          this.$message.success('更新成功')
        })
        .catch(()=> {
          this.$message({
            type:'error',
            message:'更新失败'
          })
        })
      });
    },
  },
  // 计算属性
  computed: {
    // 取出级联选择器第三级的id
    catId() {
      if (this.selectKeys.length !== 3) {
        return null;
      }
      return this.selectKeys[this.selectKeys.length - 1];
    },
    // 添加参数对话框的标题
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.cascader_header {
  margin: 15px 0;
  span {
    margin-right: 5px;
  }
}
$margin: 10px;
.expand_box {
  padding: 20px 50px;
  .el-tag {
    margin: $margin;
  }
  .input-tag {
    width: 120px;
    margin: $margin;
  }
  .button-new-tag {
    margin: $margin;
  }
}
</style>